-- ============================================
-- ROCKET CASINO - MACHINE A SOUS (version visuelle)
-- Architecture :
--   - Le COMPUTER : uniquement la connexion au clavier physique
--     (pseudo + mot de passe). Rien d'autre ne se joue ici.
--   - Le MONITOR : bannière de repos (Poke Ball qui tourne) tant que
--     personne n'est connecte, puis le jeu complet (100% tactile,
--     mise/tourner/quitter) une fois connecte.
--
-- Fichier requis dans le meme dossier : client_solde.lua
-- ============================================

local bank = dofile("client_solde.lua")
math.randomseed(os.epoch and os.epoch("utc") or os.time())

local FRAME_DELAY = 0.1
local ROTATION_SPEED = 0.22
local SUBTITLE_TEXT = "   *** PREPARE FOR TROUBLE * MAKE IT DOUBLE ***   BIENVENUE AU ROCKET CASINO   *** LES JACKPOTS SONT (PRESQUE) GARANTIS ***   "
local BET_MIN, BET_MAX, BET_STEP = 1, 20, 1

-- currentPlayer = pont entre la boucle du computer (login) et celle du
-- moniteur (jeu). nil = personne connecte.
local currentPlayer = nil

-------------------------------
-- MONITEUR
-------------------------------
local mon = peripheral.find("monitor")
if not mon then
    error("Aucun moniteur trouve ! Connecte un Advanced Monitor a cet ordinateur.", 0)
end

mon.setTextScale(0.5)
mon.setBackgroundColor(colors.black)
mon.clear()
local W, H = mon.getSize()

-------------------------------
-- OUTILS DE DESSIN BAS NIVEAU (canvas pixel + blit)
-------------------------------

local function newCanvas(bg)
    local c = {}
    for y = 1, H do
        c[y] = {}
        for x = 1, W do
            c[y][x] = { bg = bg, ch = " ", fg = colors.white }
        end
    end
    return c
end

local function px(canvas, x, y, bg, ch, fg)
    x, y = math.floor(x + 0.5), math.floor(y + 0.5)
    if x >= 1 and x <= W and y >= 1 and y <= H then
        local cell = canvas[y][x]
        if bg then cell.bg = bg end
        if ch then
            cell.ch = ch
            cell.fg = fg or cell.fg
        end
    end
end

local function render(canvas)
    local toBlit = colors.toBlit
    for y = 1, H do
        local row = canvas[y]
        local chars, fgs, bgs = {}, {}, {}
        for x = 1, W do
            local cell = row[x]
            chars[x] = cell.ch
            fgs[x] = toBlit(cell.fg)
            bgs[x] = toBlit(cell.bg)
        end
        mon.setCursorPos(1, y)
        mon.blit(table.concat(chars), table.concat(fgs), table.concat(bgs))
    end
end

local function fillEllipse(canvas, cx, cy, rx, ry, color)
    if rx <= 0 or ry <= 0 then return end
    for y = math.floor(cy - ry), math.ceil(cy + ry) do
        local dy = (y - cy) / ry
        local t = 1 - dy * dy
        if t >= 0 then
            local dx = rx * math.sqrt(t)
            for x = math.floor(cx - dx), math.ceil(cx + dx) do
                px(canvas, x, y, color)
            end
        end
    end
end

local function fillRect(canvas, x1, y1, x2, y2, color)
    for y = y1, y2 do
        for x = x1, x2 do
            px(canvas, x, y, color)
        end
    end
end

-- Pilule/stade (rectangle a bouts arrondis), utilisee pour les compteurs
local function fillPill(canvas, x1, y1, x2, y2, color)
    local ry = (y2 - y1) / 2
    local cy = (y1 + y2) / 2
    if x2 - x1 > 2 * ry then
        fillRect(canvas, x1 + ry, y1, x2 - ry, y2, color)
    end
    fillEllipse(canvas, x1 + ry, cy, ry, ry, color)
    fillEllipse(canvas, x2 - ry, cy, ry, ry, color)
end

local function fillTriangleUp(canvas, cx, baseY, tipY, halfWidth, color)
    local height = baseY - tipY
    if height <= 0 then return end
    for y = tipY, baseY do
        local f = (y - tipY) / height
        local w = halfWidth * f
        for x = math.floor(cx - w), math.ceil(cx + w) do
            px(canvas, x, y, color)
        end
    end
end

local function fillTriangleDown(canvas, cx, baseY, tipY, halfWidth, color)
    local height = tipY - baseY
    if height <= 0 then return end
    for y = baseY, tipY do
        local f = (tipY - y) / height
        local w = halfWidth * f
        for x = math.floor(cx - w), math.ceil(cx + w) do
            px(canvas, x, y, color)
        end
    end
end

local function fillTriangleSide(canvas, baseX, tipX, cy, halfHeight, color)
    local width = tipX - baseX
    if width == 0 then return end
    local step = width > 0 and 1 or -1
    for x = baseX, tipX, step do
        local f = (x - baseX) / width
        local hh = halfHeight * (1 - f)
        for y = math.floor(cy - hh), math.ceil(cy + hh) do
            px(canvas, x, y, color)
        end
    end
end

-------------------------------
-- MINI POLICE PIXEL 5x7 (titre + "R" de la balle)
-------------------------------

local FONT = {
    R = { "####.", "#...#", "#...#", "####.", "#..#.", "#...#", "#...#" },
    O = { ".###.", "#...#", "#...#", "#...#", "#...#", "#...#", ".###." },
    C = { ".####", "#....", "#....", "#....", "#....", "#....", ".####" },
    K = { "#...#", "#..#.", "#.#..", "##...", "#.#..", "#..#.", "#...#" },
    E = { "#####", "#....", "#....", "####.", "#....", "#....", "#####" },
    T = { "#####", "..#..", "..#..", "..#..", "..#..", "..#..", "..#.." },
    A = { ".###.", "#...#", "#...#", "#####", "#...#", "#...#", "#...#" },
    S = { ".####", "#....", "#....", ".###.", "....#", "....#", "####." },
    I = { "#####", "..#..", "..#..", "..#..", "..#..", "..#..", "#####" },
    N = { "#...#", "##..#", "#.#.#", "#..##", "#...#", "#...#", "#...#" },
}

local function drawGlyph(canvas, pattern, x0, y0, scale, color)
    for row = 1, #pattern do
        local line = pattern[row]
        for col = 1, #line do
            if line:sub(col, col) == "#" then
                for sy = 0, scale - 1 do
                    for sx = 0, scale - 1 do
                        px(canvas, x0 + (col - 1) * scale + sx, y0 + (row - 1) * scale + sy, color)
                    end
                end
            end
        end
    end
end

local function drawText(canvas, x, y, text, fg, bg)
    for i = 1, #text do
        px(canvas, x + i - 1, y, bg, text:sub(i, i), fg)
    end
end

-------------------------------
-- BANNIERE DE REPOS
-------------------------------

local CHASE_COLORS = { colors.yellow, colors.orange, colors.red, colors.orange }
local function drawMarquee(canvas, tick)
    local n = #CHASE_COLORS
    for x = 1, W do
        local c = CHASE_COLORS[((x + tick) % n) + 1]
        px(canvas, x, 1, c)
        px(canvas, x, H, c)
    end
    for y = 1, H do
        local c = CHASE_COLORS[((y + tick) % n) + 1]
        px(canvas, 1, y, c)
        px(canvas, W, y, c)
    end
end

local ACCENT_COLORS = { colors.yellow, colors.orange, colors.white, colors.orange }
local function drawBigTitle(canvas, tick, word1, word2, redIdx1, redIdx2)
    local LETTER_W, GAP_W, WORD_GAP = 5, 1, 4

    local function wordUnits(word)
        return #word * LETTER_W + (#word - 1) * GAP_W
    end
    local totalUnits = wordUnits(word1) + WORD_GAP + wordUnits(word2)

    local scale = math.max(1, math.floor((W - 6) / totalUnits))
    local totalWidth = totalUnits * scale
    local startX = math.max(2, math.floor((W - totalWidth) / 2) + 1)
    local startY = 3

    local accent = ACCENT_COLORS[(math.floor(tick / 3) % #ACCENT_COLORS) + 1]

    local function drawWord(word, x, redLetterIndex)
        for i = 1, #word do
            local letter = word:sub(i, i)
            local pattern = FONT[letter]
            local color = (redLetterIndex and i == redLetterIndex) and colors.red or accent
            if pattern then
                drawGlyph(canvas, pattern, x + 1, startY + 1, scale, colors.black)
                drawGlyph(canvas, pattern, x, startY, scale, color)
            end
            x = x + (LETTER_W + GAP_W) * scale
        end
        return x
    end

    local cursor = startX
    cursor = drawWord(word1, cursor, redIdx1)
    cursor = cursor + (WORD_GAP - GAP_W) * scale
    drawWord(word2, cursor, redIdx2)

    return startY + 7 * scale + 2
end

local function drawSubtitle(canvas, tick)
    local y = H - 2
    local len = #SUBTITLE_TEXT
    local offset = tick % len
    local scrolled = SUBTITLE_TEXT:sub(offset + 1) .. SUBTITLE_TEXT:sub(1, offset)
    local visible = scrolled:sub(1, math.max(0, W - 4))
    drawText(canvas, 3, y, visible, colors.yellow, colors.black)
end

local function drawPokeball(canvas, cx, cy, r, angle)
    local squish = math.max(0.12, math.abs(math.cos(angle)))
    local rx = r * squish
    local ry = r

    fillEllipse(canvas, cx, cy, rx + 1.2, ry + 1.2, colors.gray)

    for y = math.floor(cy - ry), math.ceil(cy + ry) do
        local dy = (y - cy) / ry
        local t = 1 - dy * dy
        if t >= 0 then
            local dx = rx * math.sqrt(t)
            local color
            if y < cy - ry * 0.08 then
                color = colors.black
            elseif y > cy + ry * 0.08 then
                color = colors.red
            else
                color = colors.lightGray
            end
            for x = math.floor(cx - dx), math.ceil(cx + dx) do
                px(canvas, x, y, color)
            end
        end
    end

    for x = math.floor(cx - rx), math.ceil(cx + rx) do
        px(canvas, x, cy, colors.black)
    end

    local buttonR = math.max(1, r * 0.28 * squish)
    fillEllipse(canvas, cx, cy, buttonR + 0.6, buttonR + 0.6, colors.black)
    fillEllipse(canvas, cx, cy, buttonR, buttonR, colors.white)
    fillEllipse(canvas, cx, cy, buttonR * 0.5, buttonR * 0.5, colors.lightGray)

    if squish > 0.55 then
        local scale = math.max(1, math.floor(r * squish / 5))
        local rx0 = math.floor(cx - 2 * scale)
        local ry0 = math.floor(cy - ry * 0.75)
        for dx = -1, 1 do
            for dy = -1, 1 do
                if dx ~= 0 or dy ~= 0 then
                    drawGlyph(canvas, FONT.R, rx0 + dx, ry0 + dy, scale, colors.black)
                end
            end
        end
        drawGlyph(canvas, FONT.R, rx0, ry0, scale, colors.red)
    end
end

local function drawIdleFrame(tick, angle, flashHint)
    local canvas = newCanvas(colors.black)
    drawMarquee(canvas, tick)
    local contentTop = drawBigTitle(canvas, tick, "ROCKET", "CASINO", 1, 1)

    local centerX = math.floor(W / 2)
    local availableH = math.max(6, (H - 3) - contentTop)
    local centerY = contentTop + math.floor(availableH / 2)
    local shapeR = math.floor(math.min(W * 0.22, availableH * 0.45))
    drawPokeball(canvas, centerX, centerY, shapeR, angle)

    local hint = flashHint and "*** VA TAPER TON PSEUDO SUR L'ORDINATEUR ! ***"
        or "Connecte-toi sur l'ordinateur pour jouer"
    local hx = math.max(2, math.floor((W - #hint) / 2) + 1)
    drawText(canvas, hx, math.min(H - 4, centerY + shapeR + 2), hint,
        flashHint and colors.red or colors.white, colors.black)

    drawSubtitle(canvas, tick)
    render(canvas)
end

-- Boucle de repos : tourne tant que personne n'est connecte. Un touche
-- pendant cette periode fait clignoter un message qui renvoie vers le
-- computer (pas de moyen technique de forcer l'ouverture de son ecran).
local function idleLoop()
    local tick, angle = 0, 0
    local flashTicks = 0
    while currentPlayer == nil do
        drawIdleFrame(tick, angle, flashTicks > 0)
        if flashTicks > 0 then flashTicks = flashTicks - 1 end
        angle = angle + ROTATION_SPEED
        tick = tick + 1

        local timerId = os.startTimer(FRAME_DELAY)
        local waiting = true
        while waiting do
            local ev, a = os.pullEvent()
            if ev == "timer" and a == timerId then
                waiting = false
            elseif ev == "monitor_touch" then
                flashTicks = math.floor(1.5 / FRAME_DELAY)
            end
        end
    end
end

-------------------------------
-- SYMBOLES DE LA MACHINE A SOUS (dessins originaux)
-------------------------------

local function drawSymbolSeven(canvas, cx, cy, r)
    fillEllipse(canvas, cx, cy, r, r, colors.black)
    fillEllipse(canvas, cx, cy, r * 0.8, r * 0.8, colors.red)
    local scale = math.max(1, math.floor(r / 3))
    drawGlyph(canvas, FONT.T, math.floor(cx - 2.5 * scale), math.floor(cy - 3.5 * scale), scale, colors.yellow)
end

local function drawSymbolStar(canvas, cx, cy, r)
    fillTriangleUp(canvas, cx, cy, cy - r, r * 0.24, colors.yellow)
    fillTriangleDown(canvas, cx, cy, cy + r, r * 0.24, colors.yellow)
    fillTriangleSide(canvas, cx, cx - r, cy, r * 0.24, colors.yellow)
    fillTriangleSide(canvas, cx, cx + r, cy, r * 0.24, colors.yellow)
    fillEllipse(canvas, cx, cy, r * 0.22, r * 0.22, colors.white)
end

local function drawSymbolFlame(canvas, cx, cy, r)
    fillEllipse(canvas, cx, cy + r * 0.15, r * 0.7, r * 0.6, colors.red)
    fillTriangleUp(canvas, cx, cy + r * 0.15, cy - r, r * 0.55, colors.red)
    fillEllipse(canvas, cx, cy + r * 0.25, r * 0.45, r * 0.4, colors.orange)
    fillTriangleUp(canvas, cx, cy + r * 0.25, cy - r * 0.55, r * 0.32, colors.orange)
    fillEllipse(canvas, cx, cy + r * 0.35, r * 0.2, r * 0.2, colors.yellow)
end

local function drawSymbolCoin(canvas, cx, cy, r)
    fillEllipse(canvas, cx, cy, r, r, colors.brown)
    fillEllipse(canvas, cx, cy, r * 0.8, r * 0.8, colors.orange)
    fillEllipse(canvas, cx, cy, r * 0.55, r * 0.55, colors.yellow)
end

local function drawSymbol(canvas, id, cx, cy, r)
    if id == "BALL" then
        drawPokeball(canvas, cx, cy, r, 0)
    elseif id == "SEVEN" then
        drawSymbolSeven(canvas, cx, cy, r)
    elseif id == "STAR" then
        drawSymbolStar(canvas, cx, cy, r)
    elseif id == "FLAME" then
        drawSymbolFlame(canvas, cx, cy, r)
    elseif id == "COIN" then
        drawSymbolCoin(canvas, cx, cy, r)
    end
end

-------------------------------
-- TABLE DES GAINS
-------------------------------

local SYMBOLS = {
    { id = "BALL",  weight = 1, mult = 20 },
    { id = "SEVEN", weight = 2, mult = 10 },
    { id = "STAR",  weight = 3, mult = 7 },
    { id = "FLAME", weight = 4, mult = 5 },
    { id = "COIN",  weight = 5, mult = 3 },
}

local TOTAL_WEIGHT = 0
for _, s in ipairs(SYMBOLS) do TOTAL_WEIGHT = TOTAL_WEIGHT + s.weight end

local MULT_BY_ID = {}
for _, s in ipairs(SYMBOLS) do MULT_BY_ID[s.id] = s.mult end

local function pickSymbol()
    local roll = math.random(TOTAL_WEIGHT)
    local acc = 0
    for _, s in ipairs(SYMBOLS) do
        acc = acc + s.weight
        if roll <= acc then return s.id end
    end
    return SYMBOLS[#SYMBOLS].id
end

local function evaluateWin(symbols, bet)
    if symbols[1] == symbols[2] and symbols[2] == symbols[3] then
        local mult = MULT_BY_ID[symbols[1]] or 1
        return bet * mult, "JACKPOT ! 3x " .. symbols[1] .. " (x" .. mult .. ")"
    elseif symbols[1] == symbols[2] or symbols[2] == symbols[3] or symbols[1] == symbols[3] then
        return bet, "Petit gain, mise remboursee !"
    else
        return 0, "Perdu... retente ta chance !"
    end
end

-------------------------------
-- ECRAN DE JEU (100% tactile, inspire de l'idee "medaillons colores"
-- + compteurs + bulle de dialogue, dans un style Team Rocket original)
-------------------------------

local CHIP_COLORS = { colors.lightBlue, colors.pink, colors.lime, colors.purple, colors.cyan, colors.orange }
local ROW_KEYS = { "top", "mid", "bot" }

local function drawGameScreen(tick, player, credit, lastGain, bet, reels, message)
    local canvas = newCanvas(colors.black)

    for x = 1, W do
        px(canvas, x, 1, colors.red)
        px(canvas, x, H, colors.red)
    end
    for y = 1, H do
        px(canvas, 1, y, colors.red)
        px(canvas, W, y, colors.red)
    end

    -- compteurs JETONS / GAIN
    local pillY1, pillY2 = 3, 5
    local leftX1, leftX2 = 3, math.floor(W / 2) - 1
    local rightX1, rightX2 = math.floor(W / 2) + 1, W - 2
    fillPill(canvas, leftX1, pillY1, leftX2, pillY2, colors.gray)
    fillPill(canvas, rightX1, pillY1, rightX2, pillY2, colors.gray)
    drawText(canvas, leftX1 + 2, pillY1 + 1, "JETONS " .. credit, colors.yellow, colors.gray)
    drawText(canvas, rightX1 + 2, pillY1 + 1, "GAIN " .. lastGain, colors.lime, colors.gray)

    -- grille de rouleaux en medaillons colores
    local gridTop = pillY2 + 3
    local gridBottom = H - 9
    local rowY = {
        gridTop + math.floor((gridBottom - gridTop) * 0.2),
        gridTop + math.floor((gridBottom - gridTop) * 0.5),
        gridTop + math.floor((gridBottom - gridTop) * 0.8),
    }

    local colSpacing = math.floor((W - 10) / 3)
    local colX = {}
    for c = 1, 3 do
        colX[c] = 7 + (c - 1) * colSpacing + math.floor(colSpacing / 2)
    end
    local chipR = math.max(2, math.floor(colSpacing * 0.32))

    for c = 1, 3 do
        for r = 1, 3 do
            local id = reels[c][ROW_KEYS[r]]
            local bg = CHIP_COLORS[((c + r) % #CHIP_COLORS) + 1]
            local highlight = (r == 2)
            fillEllipse(canvas, colX[c], rowY[r], chipR + 1, chipR + 1, highlight and colors.red or colors.black)
            fillEllipse(canvas, colX[c], rowY[r], chipR, chipR, bg)
            drawSymbol(canvas, id, colX[c], rowY[r], math.floor(chipR * 0.6))
        end
    end

    px(canvas, colX[1] - chipR - 3, rowY[2], nil, ">", colors.red)
    px(canvas, colX[3] + chipR + 3, rowY[2], nil, "<", colors.red)

    -- bulle de dialogue (avatar Team Rocket + message)
    local boxY1 = H - 7
    local boxY2 = H - 4
    fillRect(canvas, 2, boxY1, W - 1, boxY2, colors.white)
    fillEllipse(canvas, 5, boxY1 + 1, 1.7, 1.7, colors.black)
    fillEllipse(canvas, 5, boxY1 + 1, 1.2, 1.2, colors.red)
    drawText(canvas, 8, boxY1 + 1, message or "", colors.black, colors.white)

    -- boutons tactiles
    local buttons = {}
    local btnY = H - 2
    local cursor = 3
    local function btn(id, label, bg, fg)
        local text = " " .. label .. " "
        for i = 1, #text do
            px(canvas, cursor + i - 1, btnY, bg, text:sub(i, i), fg or colors.white)
        end
        table.insert(buttons, { id = id, x1 = cursor, x2 = cursor + #text - 1, y1 = btnY, y2 = btnY })
        cursor = cursor + #text + 1
    end
    btn("BET_DOWN", "-MISE", colors.red)
    btn("BET_UP", "+MISE", colors.green)
    btn("SPIN", "TOURNER (" .. bet .. ")", colors.orange, colors.black)
    btn("QUIT", "QUITTER", colors.gray)

    render(canvas)
    return buttons
end

-- Animation : les rouleaux s'arretent l'un apres l'autre
local function spinAnimation(player, creditDuringSpin, bet)
    local reels = {}
    for i = 1, 3 do
        reels[i] = { top = pickSymbol(), mid = pickSymbol(), bot = pickSymbol() }
    end
    local stopTicks = { 10, 16, 22 }
    local maxTick = stopTicks[3]

    for tick = 1, maxTick do
        for i, reel in ipairs(reels) do
            if tick <= stopTicks[i] then
                reel.top = reel.mid
                reel.mid = reel.bot
                reel.bot = pickSymbol()
            end
        end
        drawGameScreen(tick, player, creditDuringSpin, "...", bet, reels, "Ca tourne...")
        sleep(0.06)
    end

    return reels
end

-- Session de jeu, 100% tactile, pour un joueur deja connecte
local function runGameSession(player)
    local credit = bank.getBalance(player)
    local bet = BET_MIN
    local lastGain = 0
    local message = "Place ta mise et lance les rouleaux !"
    local reels = {
        { top = "COIN", mid = "COIN", bot = "COIN" },
        { top = "COIN", mid = "COIN", bot = "COIN" },
        { top = "COIN", mid = "COIN", bot = "COIN" },
    }
    local tick = 0
    local playing = true

    while playing do
        credit = bank.getBalance(player)
        local buttons = drawGameScreen(tick, player, credit, lastGain, bet, reels, message)
        tick = tick + 1

        local _, _, x, y = os.pullEvent("monitor_touch")
        local pressed = nil
        for _, b in ipairs(buttons) do
            if x >= b.x1 and x <= b.x2 and y >= b.y1 and y <= b.y2 then
                pressed = b.id
                break
            end
        end

        if pressed == "BET_DOWN" then
            bet = math.max(BET_MIN, bet - BET_STEP)
        elseif pressed == "BET_UP" then
            bet = math.min(BET_MAX, bet + BET_STEP)
        elseif pressed == "SPIN" then
            if credit < bet then
                message = "Solde insuffisant !"
            else
                local newBal, err = bank.addBalance(player, -bet)
                if not newBal then
                    message = err or "Erreur banque, reessaie."
                else
                    reels = spinAnimation(player, newBal, bet)
                    local gain, resultMsg = evaluateWin({ reels[1].mid, reels[2].mid, reels[3].mid }, bet)
                    if gain > 0 then
                        bank.addBalance(player, gain)
                    end
                    lastGain = gain
                    message = resultMsg
                    credit = bank.getBalance(player)
                end
            end
        elseif pressed == "QUIT" then
            playing = false
        end
    end
end

local function monitorMainLoop()
    while true do
        idleLoop()
        if currentPlayer then
            runGameSession(currentPlayer)
            currentPlayer = nil
        end
    end
end

-------------------------------
-- COMPUTER : connexion au clavier physique UNIQUEMENT
-------------------------------

local function authenticateKeyboard()
    term.setBackgroundColor(colors.black)
    term.clear()
    term.setCursorPos(1, 1)
    term.setTextColor(colors.red)
    print("=== ROCKET CASINO ===")
    term.setTextColor(colors.white)
    write("Pseudo Minecraft : ")
    local username = read()

    while true do
        write("Mot de passe : ")
        local password = read("*")
        local ok, err = bank.authenticate(username, password)
        if ok then
            term.setTextColor(colors.lime)
            print("Connecte ! Va jouer sur l'ecran mural.")
            return username
        else
            term.setTextColor(colors.red)
            print(err or "Erreur de connexion, reessaie.")
            term.setTextColor(colors.white)
        end
    end
end

local function computerLoginLoop()
    while true do
        if currentPlayer == nil then
            local player = authenticateKeyboard()
            currentPlayer = player
        end
        while currentPlayer ~= nil do
            sleep(0.5)
        end
    end
end

-------------------------------
-- LANCEMENT
-------------------------------

parallel.waitForAll(monitorMainLoop, computerLoginLoop)